<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/2/24
 * Time: 10:14
 */

namespace app\admin\model;

use think\Validate;

class User extends Common
{
    protected $name = 'admin_user';


    public function login($username, $password)
    {
        if (!$username) {
            $this->error = '账号不能为空';
            return false;
        }
        if (!$password) {
            $this->error = '密码不能为空';
            return false;
        }

        $userInfo = $this->where('username', $username)->find();
        if (!$userInfo) {
            $this->error = '帐号不存在';
            return false;
        }
        if (user_md5($password) !== $userInfo['password']) {
            $this->error = '密码错误';
            return false;
        }
        session_start();
        $info['sessionId'] = session_id();
        $info['userInfo'] = $userInfo;
        $authKey = user_md5($userInfo['username'].$userInfo['password'].$info['sessionId']);
//        $info['_AUTH_LIST_'] = $dataList['rulesList'];
        $info['authKey'] = $authKey;
        cache('Auth_'.$authKey, null);
        cache('Auth_'.$authKey, $info, config('LOGIN_SESSION_VALID'));

        // 返回信息
        $data['authKey']		= $authKey;
        $data['sessionId']		= $info['sessionId'];
        $data['userInfo']		= $userInfo;
        return $data;

    }

    public function createUser($param)
    {
        $validate = new Validate([
            'username'  => 'require|unique:admin_user',
            'password' => 'require'
        ]);
        // 验证
        if (!$validate->check($param)) {
            $this->error = $validate->getError();
            return false;
        }
        $param['password'] = user_md5($param['password']);
        $this->data($param)->allowField(true)->save();
        return true;
    }
}